<template>
  <div class="mod-chat">
    <div class="chat-container">
      <!-- 左侧会话列表 -->
      <div class="session-list">
        <div class="session-header">
          <el-input
            placeholder="搜索会话"
            v-model="searchKeyword"
            clearable
            @clear="getSessionList"
            @keyup.enter.native="searchSessions">
            <el-button slot="append" icon="el-icon-search" @click="searchSessions"></el-button>
          </el-input>
        </div>
        <div class="session-items">
          <div
            v-for="session in sessionList"
            :key="session.session_id"
            :class="['session-item', { active: currentSession.session_id === session.session_id }]"
            @click="switchSession(session)">
            <div class="session-title">{{ session.title || '未命名会话' }}</div>
            <div class="session-preview">{{ session.last_message }}</div>
            <div class="session-time">{{ formatTime(session.update_time) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 右侧对话内容 -->
      <div class="chat-content" v-if="currentSession.session_id">
        <div class="chat-header">
          <span>{{ currentSession.title || '未命名会话' }}</span>
          <div class="header-actions">
            <el-button 
              type="text" 
              icon="el-icon-edit"
              @click="renameSessionHandle">重命名</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete"
              @click="deleteSessionHandle">删除会话</el-button>
          </div>
        </div>
        <div class="chat-messages" ref="messageContainer">
          <div
            v-for="(message, index) in messageList"
            :key="index"
            :class="['message-item', message.role === 'assistant' ? 'assistant' : 'user']">
            <div class="message-content">{{ message.message }}</div>
            <div class="message-time">{{ formatTime(message.createTime) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <i class="el-icon-chat-line-round"></i>
        <p>选择一个会话开始查看</p>
      </div>
    </div>
    
    <!-- 重命名对话框 -->
    <el-dialog
      title="重命名会话"
      :visible.sync="renameDialogVisible"
      width="30%">
      <el-form :model="renameForm" :rules="renameRules" ref="renameForm">
        <el-form-item prop="title">
          <el-input v-model="renameForm.title" placeholder="请输入会话标题"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRename">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      searchKeyword: '',
      sessionList: [],
      currentSession: {},
      messageList: [],
      renameDialogVisible: false,
      renameForm: {
        title: ''
      },
      renameRules: {
        title: [
          { required: true, message: '请输入会话标题', trigger: 'blur' }
        ]
      }
    }
  },
  activated () {
    this.getSessionList()
  },
  methods: {
    // 获取会话列表
    getSessionList () {
      const params = this.searchKeyword ? { keyword: this.searchKeyword } : {}
      this.$http({
        url: this.$http.adornUrl('/doc/chat/sessions/' + this.$store.state.user.id),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.sessionList = data.sessions || []
        } else {
          this.$message.error(data && data.msg ? data.msg : '获取会话列表失败')
        }
      }).catch(() => {
        this.$message.error('获取会话列表失败')
      })
    },
    // 搜索会话
    searchSessions () {
      if (!this.searchKeyword.trim()) {
        return this.getSessionList()
      }
      this.getSessionList()
    },
    // 切换会话
    switchSession (session) {
      if (!session || !session.session_id) {
        return this.$message.warning('无效的会话')
      }
      this.currentSession = session
      this.getMessageList()
    },
    // 获取消息列表
    getMessageList () {
      this.$http({
        url: this.$http.adornUrl(`/doc/chat/history/${this.currentSession.session_id}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.messageList = data.list || []
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          this.$message.error(data && data.msg ? data.msg : '获取消息列表失败')
        }
      }).catch(() => {
        this.$message.error('获取消息列表失败')
      })
    },
    // 滚动到底部
    scrollToBottom () {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    // 格式化时间
    formatTime (timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      if (isNaN(date.getTime())) return ''
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    // 重命名会话
    renameSessionHandle () {
      if (!this.currentSession.session_id) {
        return this.$message.warning('请先选择会话')
      }
      this.renameForm.title = this.currentSession.title || ''
      this.renameDialogVisible = true
    },
    // 提交重命名
    submitRename () {
      this.$refs['renameForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/doc/chat/rename/' + this.currentSession.session_id),
            method: 'post',
            data: this.$http.adornData({
              'title': this.renameForm.title
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '重命名成功',
                type: 'success',
                duration: 1500
              })
              this.renameDialogVisible = false
              this.getSessionList()
            } else {
              this.$message.error(data && data.msg ? data.msg : '重命名失败')
            }
          }).catch(() => {
            this.$message.error('重命名失败')
          })
        }
      })
    },
    // 删除会话
    deleteSessionHandle () {
      if (!this.currentSession.session_id) {
        return this.$message.warning('请先选择会话')
      }
      this.$confirm('确定要删除该会话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/doc/chat/delete/' + this.currentSession.session_id),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.currentSession = {}
                this.messageList = []
                this.getSessionList()
              }
            })
          } else {
            this.$message.error(data && data.msg ? data.msg : '删除失败')
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    }
  }
}
</script>

<style scoped>
.mod-chat {
  height: calc(100vh - 100px);
  padding: 20px;
}

.chat-container {
  display: flex;
  height: 100%;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.session-list {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.session-header {
  padding: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.session-items {
  flex: 1;
  overflow-y: auto;
}

.session-item {
  padding: 15px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.session-item:hover {
  background: #f5f7fa;
}

.session-item.active {
  background: #ecf5ff;
}

.session-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.session-preview {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.session-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 20px;
  max-width: 80%;
}

.message-item.user {
  margin-left: auto;
}

.message-item.assistant {
  margin-right: auto;
}

.message-content {
  padding: 10px 15px;
  border-radius: 4px;
  background: #f4f4f5;
  line-height: 1.5;
}

.message-item.user .message-content {
  background: #ecf5ff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 10px;
}
</style>
